"""
简化版热点获取服务 - 快速获取主要平台热点
"""
import asyncio
import json
import logging
from datetime import datetime
from typing import Dict, Any, List
import aiohttp

logger = logging.getLogger(__name__)


class SimpleHotService:
    """简化热点服务 - 使用可靠的API快速获取"""
    
    def __init__(self):
        self.session = None
        self.timeout = aiohttp.ClientTimeout(total=5)  # 5秒超时
    
    async def __aenter__(self):
        self.session = aiohttp.ClientSession(timeout=self.timeout)
        return self
    
    async def __aexit__(self, *args):
        if self.session:
            await self.session.close()
    
    async def fetch_github_trending(self) -> List[Dict[str, Any]]:
        """GitHub趋势"""
        try:
            url = "https://api.github.com/search/repositories"
            params = {'q': 'stars:>5000', 'sort': 'stars', 'order': 'desc', 'per_page': 20}
            
            async with self.session.get(url, params=params) as resp:
                if resp.status == 200:
                    data = await resp.json()
                    return [{
                        'rank': i+1,
                        'title': repo['full_name'],
                        'description': (repo.get('description') or '')[:100],
                        'url': repo['html_url'],
                        'stars': repo['stargazers_count'],
                        'source': 'github'
                    } for i, repo in enumerate(data.get('items', [])[:20])]
        except Exception as e:
            logger.error(f"GitHub失败: {e}")
        return []
    
    async def fetch_bilibili_ranking(self) -> List[Dict[str, Any]]:
        """B站排行榜"""
        try:
            url = "https://api.bilibili.com/x/web-interface/ranking/v2"
            async with self.session.get(url, params={'rid': 0}) as resp:
                if resp.status == 200:
                    data = await resp.json()
                    if data.get('code') == 0:
                        return [{
                            'rank': i+1,
                            'title': item.get('title', ''),
                            'author': item.get('owner', {}).get('name', ''),
                            'view': item.get('stat', {}).get('view', 0),
                            'url': f"https://www.bilibili.com/video/{item.get('bvid', '')}",
                            'source': 'bilibili'
                        } for i, item in enumerate(data.get('data', {}).get('list', [])[:20])]
        except Exception as e:
            logger.error(f"B站失败: {e}")
        return []
    
    async def fetch_juejin_hot(self) -> List[Dict[str, Any]]:
        """掘金热门"""
        try:
            url = "https://api.juejin.cn/recommend_api/v1/article/recommend_all_feed"
            payload = {"id_type": 2, "client_type": 2608, "sort_type": 200, "cursor": "0", "limit": 20}
            
            async with self.session.post(url, json=payload) as resp:
                if resp.status == 200:
                    data = await resp.json()
                    articles = []
                    for i, item in enumerate(data.get('data', [])[:20]):
                        info = item.get('item_info', {}).get('article_info', {})
                        articles.append({
                            'rank': i+1,
                            'title': info.get('title', ''),
                            'brief': info.get('brief_content', '')[:100],
                            'views': info.get('view_count', 0),
                            'source': 'juejin'
                        })
                    return articles
        except Exception as e:
            logger.error(f"掘金失败: {e}")
        return []
    
    async def fetch_all(self) -> Dict[str, Any]:
        """并发获取所有数据"""
        tasks = await asyncio.gather(
            self.fetch_github_trending(),
            self.fetch_bilibili_ranking(),
            self.fetch_juejin_hot(),
            return_exceptions=True
        )
        
        results = {
            'github': tasks[0] if isinstance(tasks[0], list) else [],
            'bilibili': tasks[1] if isinstance(tasks[1], list) else [],
            'juejin': tasks[2] if isinstance(tasks[2], list) else []
        }
        
        # 添加统计
        total = sum(len(v) for v in results.values())
        success = sum(1 for v in results.values() if v)
        
        return {
            'data': results,
            'stats': {
                'total_items': total,
                'successful_platforms': success,
                'timestamp': datetime.now().isoformat()
            }
        }


async def main():
    """测试"""
    logging.basicConfig(level=logging.INFO)
    
    async with SimpleHotService() as service:
        print("获取热点数据中...")
        result = await service.fetch_all()
        
        print("\n=== 热点数据 ===")
        for platform, items in result['data'].items():
            print(f"\n{platform.upper()}: {len(items)} 条")
            for item in items[:5]:
                print(f"  [{item['rank']}] {item['title'][:60]}")
        
        print(f"\n总计: {result['stats']['total_items']} 条")
        
        # 保存到文件
        with open('hot_topics_simple.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
            print(f"\n数据已保存到 hot_topics_simple.json")
        
        return result['stats']['total_items'] > 0


if __name__ == "__main__":
    result = asyncio.run(main())
    exit(0 if result else 1)